import fs from 'fs';
import path from 'path';
import env from './env.config';

const isMocking = process.env.MOCK === '1';
const isProd = process.env.NODE_ENV === 'production';
const buildTarget = process.env.BUILD || 'prod';
const envConfig = env[isProd ? buildTarget : 'dev'];
// eslint-disable-next-line no-console
isProd && console.log(`Building target: ${buildTarget}`);
const mockURL = `http://127.0.0.1:${envConfig.MOCK_PORT || 6002}`;

export default {
  ssr: false,
  target: 'static',
  generate: {
    // Dynamic params routes 无法生成路由，使用 fallback
    fallback: 'index.html',
  },
  server: {
    host: envConfig.DEV_HOST || 'localhost',
    port: envConfig.DEV_PORT || 6001,
    https: envConfig.HTTPS
      ? {
          key: fs.readFileSync(path.resolve(__dirname, 'env/certs/localhost.key')),
          cert: fs.readFileSync(path.resolve(__dirname, 'env/certs/localhost.cert')),
        }
      : false,
  },
  srcDir: 'src/',
  dir: {
    pages: 'views',
  },
  features: {
    transitions: false,
  },
  head: {
    title: '就医绿通',
    htmlAttrs: {
      lang: 'en',
    },
    meta: [
      { charset: 'utf-8' },
      {
        name: 'viewport',
        content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0,minimal-ui',
      },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' },
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      // tabbar图标库
      {
        rel: 'stylesheet',
        href: '//at.alicdn.com/t/font_2997745_zc48vafq3lk.css',
      },
    ],
  },
  css: ['~/assets/styles/index.less'],
  modules: ['@nuxtjs/proxy'],
  proxy:
    envConfig.PROXY && !isProd
      ? {
          '/main/action': {
            target: envConfig.healthBaseURL,
            changeOrigin: true,
          },
          '/auth/action': {
            target: envConfig.loginBaseURL,
            changeOrigin: true,
          },
          '/hospital/gchannel/': {
            target: envConfig.baseURL,
            changeOrigin: true,
          },
        }
      : {},
  env: {
    ...envConfig,
    healthBaseURL: isMocking ? mockURL : envConfig.PROXY && !isProd ? '/' : envConfig.healthBaseURL,
    loginBaseURL: isMocking ? mockURL : envConfig.PROXY && !isProd ? '/' : envConfig.loginBaseURL,
    baseURL: isMocking ? mockURL : envConfig.PROXY && !isProd ? '/' : envConfig.baseURL,
    BUILD_ENV: process.env.BUILD,
  },
  publicRuntimeConfig: {},
  privateRuntimeConfig: {},
  plugins: [
    { src: '@/plugins/sentry', ssr: false },
    '@/plugins/vant',
    '@/plugins/bootstrap',
    '@/plugins/locale',
    '@/plugins/apis',
    '@/plugins/storage',
  ],
  router: {
    extendRoutes(routes, resolve) {
      (function setChumkName(routes) {
        routes.forEach((route) => {
          route.chunkName = route.chunkName
            ?.split('/')
            .slice(0, route.chunkName?.startsWith('views/customer') ? 3 : 2)
            .join('/');
          route.children?.length && setChumkName(route.children);
        });
      })(routes);
      return routes.map((item) => {
        return {
          ...item,
          path: '/:site/:newCompanyId(\\d{7})' + item.path,
        };
      });
    },
    middleware: 'auth',
  },
  buildModules: ['@nuxtjs/router-extras'],
  build: {
    postcss: {
      plugins: {
        'postcss-pxtorem': {
          rootValue: 37.5,
          unitPrecision: 3,
          minPixelValue: 3,
          propList: ['*'],
        },
      },
    },
    babel: {
      // use babel.config.js
      babelrc: true,
      configFile: true,
      cacheDirectory: undefined,
    },
    optimization: {
      splitChunks: {
        chunks: 'async',
      },
    },
    splitChunks: {
      vendor: true,
      commons: true,
      runtime: true,
      pages: true,
      layouts: false,
    },
    transpile: [],
    extractCSS: true,
    loaders: {
      less: {
        lessOptions: {
          javascriptEnabled: true,
          modifyVars: {
            hack: 'true;@import "./src/assets/styles/fn.less";',
          },
        },
      },
      cssModules: {
        modules: {
          localIdentName: isProd ? '[hash:base64]' : '[path]_[name]_[local]_[hash:base64:5]',
        },
        localsConvention: 'camelCaseOnly',
      },
    },
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {
      if (ctx.isClient) {
        // https://github.com/webpack/webpack/issues/5423
        config.node = Object.assign({}, config.node, {
          fs: 'empty',
          path: 'empty',
          module: 'empty',
        });
        // https://github.com/nuxt/nuxt.js/issues/212
        // config.module.rules.push({
        //   enforce: 'pre',
        //   test: /\.(js|vue)$/,
        //   loader: 'eslint-loader',
        //   exclude: /(node_modules)/,
        //   options: {
        //     formatter: require('eslint-friendly-formatter'),
        //   },
        // });
      }
      config.output.globalObject = 'this';
      config.module.rules.push({ test: /\.pdf$/, loader: 'file-loader' });
    },
  },
  // 启动加载 loading 配置
  loadingIndicator: {
    name: 'three-bounce',
    color: '#c6cad3',
    background: 'white',
  },
  // 忽略文件的 auto build
  ignore: ['views/**/components/*', 'views/**/utils/*', 'views/**/service/*'],
};
